package per.example.arpproject.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.WriterOutputStream;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author yaozhang Li
 * @ TO DO
 * @createTime 2023/7/10 19:02
 **/
public class JsonUtil {


    public static JSONArray getJsonArrayByFilePath(String path) throws IOException {
        InputStream in = new BufferedInputStream(new FileInputStream(path));

        String conf = IOUtils.toString(in, StandardCharsets.UTF_8);

        return JSON.parseArray(conf);
    }

    public static JSONObject getJsonObjectByFilePath(String path) throws IOException {
        InputStream in = new BufferedInputStream(new FileInputStream(path));

        String conf = IOUtils.toString(in, StandardCharsets.UTF_8);

        return JSON.parseObject(conf);
    }

    public static void writeJsonFile(JSON json, String path) throws IOException {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        } else {
            String absolutePath = file.getAbsolutePath();
            String dirPath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
            File file1 = new File(dirPath);
            file1.mkdirs();

            file.createNewFile();

        }

        IOUtils.write(json.toJSONString(),new FileOutputStream(file),StandardCharsets.UTF_8);
    }



    public static void main(String[] args) throws IOException {
/*        final String jsonPath = "F:\\code\\job\\dxx\\arp\\arp-project\\document\\test.json";

        JSON json = JsonUtil.getJsonArrayByFilePath(jsonPath);
        System.out.println(json.toJSONString());

        final String jsonobjectPath = "F:\\code\\job\\dxx\\arp\\arp-project\\document\\testobject.json";
        JSON json1 = JsonUtil.getJsonObjectByFilePath(jsonobjectPath);
        System.out.println(json1);

        final String jsonWritePath = "F:\\code\\job\\dxx\\arp\\arp-project\\document\\testWrite.json";
        final String jsonstr = "{\"a\":\"b\"}";
        JsonUtil.writeJsonFile(JSONObject.parseObject(jsonstr),jsonWritePath);

        final String jsonWritePathArray = "F:\\code\\job\\dxx\\arp\\arp-project\\document\\testWriteArray.json";
        final String jsonArrayStr = "[{\"a\":\"b\"}]";
        JsonUtil.writeJsonFile(JSONObject.parseArray(jsonArrayStr),jsonWritePathArray);*/

        File file = new File("F:\\code\\job\\dxx\\arp\\spritData\\total.json");
        file.delete();
    }

}
